class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ans;
        sort(nums.begin(),nums.end());
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]>0)
                break;
            if (i && nums[i] == nums[i - 1]) 
                continue;
            int left=i+1;
            int right=nums.size()-1;
            while(left<right)
            {
                vector<int> temp;
                if(nums[i]+nums[left]+nums[right]==0)
                {
                    ans.push_back(vector<int>{nums[i], nums[left], nums[right]});
                    // 去重逻辑应该放在找到一个三元组之后
                    while (right > left && nums[right] == nums[right - 1]) 
                        right--;
                    while (right > left && nums[left] == nums[left + 1]) 
                        left++;
                    // 找到答案时，双指针同时收缩
                    right--;
                    left++;
                }
                else if(nums[i]+nums[left]+nums[right]>0)
                {
                    right--;
                }
                else
                {
                    left++;
                }
            }
        }
       
        return ans;
    }
};